package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dtos.WmNewsPageReqDto;
import com.heima.model.media.pojos.WmNews;
import com.heima.model.media.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @Author 96558
 * @Date 2021/1/15 21:45
 * @Version 1.0
 **/
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    /**
     * 查询所有自媒体文章
     *
     * @param dto
     * @return
     */

    @Value("${file.oss.web-site}")
    String webSite;

    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1.参数检查
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //2.条件封装
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();

        //关键字模糊查询
        if (StringUtils.isNotEmpty(dto.getKeyword())) {
            wrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        //文章状态
        if (dto.getStatus() != null) {
            wrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        //频道id
        if (dto.getChannelId() != null) {
            wrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //文章状态
        if (dto.getStatus() != null) {
            wrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        //发布时间
        if (dto.getEndPubDate() != null && dto.getBeginPubDate() != null) {
            wrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }

        //userid
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser == null) {
            CustException.cust(AppHttpCodeEnum.NEED_ADMIND);
        }
        wrapper.eq(WmNews::getUserId, wmUser.getId());
        //时间倒叙
        wrapper.orderByDesc(WmNews::getCreatedTime);
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmNews> pageResult = page(page, wrapper);

        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(),
                (int) pageResult.getTotal(), pageResult.getRecords());
        //3.返回结果
        result.setHost(webSite);

        return result;
    }


}
